var express = require("express");
var router = express.Router();
const getTime = require("../../utils/getTime");
const policyModel = require("../../models/policyModel");
const fs = require("fs");
const path = require("path");

// 图片上传的接口
router.post("/uploadImg1", (req, res) => {
  let oldName = req.files[0].filename;
  let originalname = req.files[0].originalname;
  // 取无后缀的文件名
  let ex_name = originalname.split(".")[0];
  //防止文件名重复，为文件名加上时间戳
  let fileName = ex_name + "-" + Date.now() + path.extname(originalname);
  fs.renameSync("./public/upload/" + oldName, "./public/upload/" + fileName);
  return res.send({
    errno: 0,
    data: [
      {
        url: "http://localhost:3000/upload/" + fileName,
        alt: "",
        href: "",
      },
    ],
  });
});

// 查询
router.get("/policy/search", (req, res) => {
  let { title } = req.query;
  const regex = new RegExp(title);
  policyModel
    .find({ title: regex })
    .select({ _v: 0 })
    .sort({ time: -1 })
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          msg: "政策数据为空",
          data: data,
        });
      }
      return res.json({
        code: 200,
        msg: "查询成功",
        data: data,
        total:data.length
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 新增
router.post("/policy/add", (req, res) => {
  let { title, content } = req.body;
  let time = getTime(new Date());
  policyModel
    .create({ title, content, time })
    .then((data) => {
      if (!data) {
        return res.json({
          code: -1,
          msg: "新增失败",
          data: null,
        });
      }
      return res.json({
        code: 200,
        msg: "新增成功",
        data: data,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 修改
router.post("/policy/update", (req, res) => {
  let { _id, title, content } = req.body;
  let time = getTime(new Date());
  policyModel
    .updateOne({ _id }, { title, content, time })
    .then((data) => {
      if (!data.acknowledged) {
        return res.json({
          code: -1,
          msg: "修改失败",
          data: null,
        });
      }
      return res.json({
        code: 200,
        msg: "信息修改成功~",
        data: null,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 获取助农政策表
router.get("/policy/info", (req, res) => {
  let { pageNo, pageSize } = req.query;
  if (pageNo === "undefined" || pageSize === "undefined") {
    policyModel
      .find()
      .select({ _v: 0 })
      .sort({ time: -1 })
      .then((data) => {
        if (data.length === 0) {
          return res.json({
            code: 200,
            msg: "数据为空",
            data: data,
          });
        }
        return res.json({
          code: 200,
          msg: "获取政策信息成功",
          data: data,
        });
      })
      .catch((err) => {
        return res.json({
          code: "1001",
          msg: "数据库读取失败~~~",
          data: null,
        });
      });
  } else {
    policyModel
      .find()
      .then((result) => {
        if (result.length === 0) {
          return res.json({
            code: 200,
            msg: "政策数据为空",
            data: null,
          });
        } else {
          policyModel
            .find()
            .select({ _v: 0 })
            .sort({ time: -1 })
            .skip((pageNo - 1) * pageSize)
            .limit(pageSize)
            .then((data) => {
              let total = result.length;
              return res.json({
                code: 200,
                msg: "获取政策信息成功",
                data: data,
                total: total,
              });
            })
            .catch((err) => {
              return res.json({
                code: "1001",
                msg: "数据库读取失败~~~",
                data: null,
              });
            });
        }
      })
      .catch((err) => {
        return res.json({
          code: "1001",
          msg: "数据库读取失败~",
          data: null,
        });
      });
  }
});

// 删除单条政策
router.post("/policy/remove", (req, res) => {
  let { _id } = req.body;
  policyModel
    .deleteOne({ _id })
    .then((result) => {
      if (result.deletedCount !== 0) {
        return res.json({
          code: 200,
          msg: "删除成功",
          data: null,
        });
      }
      return res.json({
        code: -1,
        msg: "删除失败",
        data: null,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~",
        data: null,
      });
    });
});

// 批量删除
router.post("/policy/delBatch", (req, res) => {
  policyModel
    .deleteMany({ _id: { $in: req.body } })
    .then((result) => {
      if (result.deletedCount !== 0) {
        return res.json({
          code: 200,
          msg: "删除成功",
          data: null,
        });
      }
      return res.json({
        code: -1,
        msg: "删除失败",
        data: null,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~",
        data: null,
      });
    });
});

module.exports = router;
